package org.dey.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.dey.constant.MessageConstant;
import org.dey.entity.Result;
import org.dey.mapper.UserMapper;
import org.dey.pojo.User;
import org.dey.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author deyran
 * @classname
 * @see ServiceImpl
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> USER_LIST() {
        return userMapper.USERS();
    }

    @Override
    public Result<User> LOGIN(User user) {
        Result<User> result = new Result<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername()).eq("password", user.getPassword());
        User one = this.getOne(queryWrapper);
        if (one != null) {
            result.setFlag(true);
            result.setMessage(MessageConstant.LOGIN_SUCCESS);
            result.setData(one);
        } else {
            result.setFlag(false);
            result.setMessage(MessageConstant.LOGIN_SUCCESS);
        }
        return result;
    }

    @Override //用于用户注册
    public int insertUser(User user) {
        String password = user.getPassword();
        //对密码进行md5加密
        String passwordSalt = String.valueOf(System.currentTimeMillis());
        // 设置盐值
        user.setPassword(passwordSalt);
        // /对密码进行盐值 xiami 循环加密两次
        Md5Hash md5Hash = new Md5Hash(password, passwordSalt, 2); //对密码进行盐值 循环加密两次
        user.setPassword(md5Hash.toString());
        System.out.println("user = " + user);
        return userMapper.insert(user); //注册用户
    }

    @Override
    public List<User> oneUser(Integer id, String username) {
        return userMapper.findAllByIdUsers(id, username);
    }

    @Override
    public User getUser(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        return this.getOne(wrapper);
    }

}
